package com.jackrain.nea.fc.vp.mapper;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.jdbc.SQL;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * @author xuxisnhuai
 */
@Mapper
public interface ViewCvipinteftpMapper {


    /**
     * 查询VIP类型ID
     *
     * @param ecode
     * @return
     */
    @Select("SELECT ID FROM VP_C_VIPTYPEGROUP WHERE ECODE = #{ecode}")
    Long selecttypegroupid(String ecode);




    @InsertProvider(type = CVipInteftpSqlProvider.class, method = "insertSql")
    /**
     *插入数据
     * @param jsonObject
     * @return
     */
    int insert(JSONObject jsonObject);


    class CVipInteftpSqlProvider {

        public String insertCvipbatch(HashMap map) {
            List<HashMap> list = (List<HashMap>) map.get("list");
            StringBuilder sb = new StringBuilder();
            StringBuilder keySb = new StringBuilder();
            sb.append("INSERT INTO VP_C_VIP_INTEFTP(");
            Set<String> keySet = list.get(0).keySet();
            for (String key : keySet) {
                sb.append(key + ",");
                keySb.append("#'{'list[{0}]." + key + "},");
            }
            keySb.deleteCharAt(keySb.length() - 1);
            sb.deleteCharAt(sb.length() - 1);
            sb.append(") VALUES ");

            MessageFormat mf = new MessageFormat("(" + keySb.toString() + ")");
            for (int i = 0; i < list.size(); i++) {
                sb.append(mf.format(new Object[]{i}));
                if (i < list.size() - 1) {
                    sb.append(",");
                }
            }

            return sb.toString();
        }

        public String updateSql(JSONObject map) {
            return new SQL() {
                {
                    UPDATE("VP_C_VIP_INTEFTP");
                    for (String key : map.keySet()) {
                        String id = "ID";
                        if (!id.equals(key)) {
                            SET(key + "= #{" + key + "}");
                        }
                    }
                    WHERE("ID = #{ID}");
                }
            }.toString();
        }

        public String insertSql(JSONObject jo) {
            return new SQL() {
                {
                    INSERT_INTO("VP_C_VIP_INTEFTP");
                    for (String key : jo.keySet()) {
                        VALUES(key, "#{" + key + "}");
                    }
                }
            }.toString();
        }

    }


}
